using System;
using System.Linq;
using Avalonia.Controls.Notifications;
using Avalonia.Threading;
using AvaloniaApplication1.IServices;
using AvaloniaApplication1.Models;
using AvaloniaApplication1.Models.DTOModel;
using AvaloniaApplication1.Util;
using AvaloniaApplication1.Views.CardView;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using SukiUI.Dialogs;

namespace AvaloniaApplication1.ViewModels.CardViewModel;
/// <summary>
/// mqtt设备卡片视图模型 （中间类，没有View）
/// </summary>
public partial class MqttDeviceCardViewModel : ObservableObject
{
    [ObservableProperty] private string _deviceId;
    [ObservableProperty] private IMqttDeviceManager _deviceManager;

    [ObservableProperty] private string _deviceName;
    [ObservableProperty] private string _host;
    [ObservableProperty] private int _port;
    [ObservableProperty] private bool _isConnected;

    public Action<MqttDeviceCardViewModel> OnRemoveMqttDevice;
    
    [ObservableProperty]
    private ISukiDialogManager _dialogManager;
    


    public MqttDeviceCardViewModel(MqttDeviceModel mqttDeviceModel, IMqttDeviceManager deviceManager,
        ISukiDialogManager dialogManager)
    {
        DeviceManager = deviceManager;
        DialogManager = dialogManager;
        DeviceManager.DeviceStatusChanged += DeviceStatusChanged;

        DeviceId = mqttDeviceModel.DeviceId;
        DeviceName = DeviceManager.GetDevice(DeviceId)?.DeviceId ?? "Unknown";
        Host = DeviceManager.GetDevice(DeviceId)?.Server ?? "Unknown";
        Port = DeviceManager.GetDevice(DeviceId)?.Port ?? 0000;
        IsConnected = DeviceManager.GetDevice(DeviceId)?.IsConnected ?? false;
    }

    [RelayCommand]
    public void ConnectMqttDevice(string selectDeviceId)
    {
        Dispatcher.UIThread.InvokeAsync(() =>
        {
            var device = DeviceManager.GetDevice(selectDeviceId);
            if (device == null)
            {
                DialogManager.CreateDialog().WithContent("设备不存在").WithActionButton("关闭", _ => { }, true)
                    .TryShow();
                return;
            }

            if (DeviceManager.IsDeviceConnected(selectDeviceId))
            {
                DialogManager.CreateDialog().WithContent("设备已连接").WithActionButton("关闭", _ => { }, true)
                    .TryShow();
                return;
            }

            var result = DeviceManager.ConnectDeviceAsync(DeviceId);
            if (result.IsCompleted)
            {
                //更新设备状态
                IsConnected = DeviceManager.IsDeviceConnected(selectDeviceId);
                //DeviceModel.IsConnected = true;
                DialogManager.CreateDialog().WithContent("已连接设备").WithActionButton("关闭", _ => { }, true)
                    .TryShow();
            }
        });
    }

    /// <summary>
    /// 设备状态更新
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e">更新的设备信息包括设备id设备连接状态</param>
    private void DeviceStatusChanged(object? sender, DeviceStatusEventArgs e)
    {
        if (e.DeviceId == DeviceId)
        {
            Dispatcher.UIThread.InvokeAsync(() =>
            {
                IsConnected = e.IsConnected;
                if (e.IsConnected)
                {
                    DialogManager.CreateDialog().WithContent("已连接设备").WithActionButton("关闭", _ => { }, true)
                        .TryShow();
                }

                if (!e.IsConnected)
                {
                    DialogManager.CreateDialog().WithContent("已断开设备").WithActionButton("关闭", _ => { }, true)
                        .TryShow();
                }
            });
        }
    }

    [RelayCommand]
    public void RemoveDeviceCard()
    {
        Dispatcher.UIThread.InvokeAsync(() =>
        {
            // 删除设备
            var result = DeviceManager.RemoveDeviceAsync(DeviceId);
            if (result.Result)
            {
                // 通知DevicePageViewModel 刷新设备列表
                OnRemoveMqttDevice?.Invoke(this);
                DialogManager.CreateDialog().WithContent("已成功移除设备").WithActionButton("关闭", _ => { }, true)
                    .TryShow();
            }
            else
            {
                // 删除设备失败
                DialogManager.CreateDialog().WithContent("未移除设备，请检查设备是否断开").WithActionButton("关闭", _ => { }, true)
                    .TryShow();
            }
        });
    }

    [RelayCommand]
    public void DisconnectMqttDevice(string selectDeviceId)
    {
        Dispatcher.UIThread.InvokeAsync(() => { DeviceManager.DisconnectDeviceAsync(selectDeviceId); });
    }

    [RelayCommand]
    public void DeviceSettingShow(string deviceId)
    {
        // 确保在 UI 线程执行
        Dispatcher.UIThread.InvokeAsync(() =>
        {
            var result = DeviceManager.GetDevice(deviceId);
            if (result != null)
            {
                // 创建 ViewModel 实例
                var deviceSettingViewModel = new DeviceSettingViewModel(DeviceManager, deviceId);

                var deviceSettingView = new DeviceSettingView
                {
                    DataContext = deviceSettingViewModel
                };

                DialogManager.CreateDialog()
                    .WithContent(deviceSettingView)
                    .WithActionButton("关闭", _ => { }, true).TryShow();
            }

            DialogManager.CreateDialog()
                .WithContent("设备卡片不存在")
                .WithActionButton("关闭", _ => { }, true).OfType(NotificationType.Error).TryShow();
        });
    }
}